package com.bobo.cretrofit.interceptor;


import android.util.Log;

import com.bobo.cretrofit.ApiHelper;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.List;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Retrofit动态配置Baseurl处理拦截器
 * <pre><code>
 * &#64;Headers({"Base-URL: http:www.baidu.com/a/b"})
 * &#64;GET("/")
 * ...
 * </code></pre>
 * Created by cocolove2 on 2018/7/10.
 */
public class BaseUrlSelectInterceptor implements Interceptor {
    private static final String TAG = "UrlSelectInterceptor";
    private static final String KEY_BASE_URL = "Base-URL";
    /**
     * 默认配置baseurl
     */
    private String mBaseUrl;

    public BaseUrlSelectInterceptor(String baseUrl) {
        mBaseUrl = baseUrl;
    }

    @NotNull
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        String url = request.url().toString();
        String tmpBaseUrl = obtainDomainNameFromHeaders(request);
        Log.d(TAG, "旧url:" + url);
        if (tmpBaseUrl != null) {
            //重新拼装url
            url = tmpBaseUrl + url.replace(mBaseUrl, "");
        }
        Log.d(TAG, "新url:" + url);
        request = request.newBuilder().removeHeader(KEY_BASE_URL).url(url).build();
        return chain.proceed(request);
    }

    /**
     * 从 {@link Request#header(String)} 中取出 DomainName
     *
     * @param request {@link Request}
     * @return DomainName
     */
    private String obtainDomainNameFromHeaders(Request request) {
        List<String> headers = request.headers(KEY_BASE_URL);
        if (headers.size() == 0)
            return null;
        if (headers.size() > 1)
            throw new IllegalArgumentException("Only one Domain-Name in the headers");
        String value = request.header(KEY_BASE_URL);
        if (value == null) {
            return null;
        }
        //若是url格式则直接返回，不是则从字典中取
        if (value.toLowerCase().startsWith("http")) {
            return value;
        } else {
            return ApiHelper.getInstance().getBaseUrl(value);
        }
    }
}
